#!/bin/bash

# immediately fail if an error occurs
set -e


if [[ -n "$GK_COUCHDB" ]]; then
  echo "Using existing CouchDB on :5984"
  curl -sX DELETE $GK_COUCHDB/{installations,npm,payments,repositories,monorepo}-staging 2>&1 > /dev/null
else
  echo "Starting CouchDB via Docker"
  docker rm -fv gk-couchdb || true
  docker run -d -p 5984:5984 --name gk-couchdb apache/couchdb:2.3.1
fi

TIMEOUT=280
TRIES=0
printf 'Waiting for CouchDB to be available to us'

until $(curl --output /dev/null --silent --head --fail http://localhost:5984); do
  printf '.'
  TRIES=$TRIES+1

  if [[ $TRIES -eq $TIMEOUT ]]; then
    echo 'Timed out waiting for CouchDB to be available'
    exit 1
  fi

  sleep 1
done

# speed up couchdb operations
curl -sX PUT http://localhost:5984/_node/_local/_config/couchdb/delayed_commits -d '"true"' > /dev/null 2>&1
